package com.example.demo.handler;

import com.example.demo.config.ResponseHelper;
import com.example.demo.config.ResponseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author yuy
 * <p>
 * 监听全局异常
 * <p>
 * 2018年11月13日
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 异常信息打印日志
     *
     * @param resp
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseModel<String> printLog(Exception e) {
        logger.error(e.getMessage(), e);
        return ResponseHelper.internalServerError("服务器错误！请稍后再试！");
    }

    /**
     * 处理所有接口数据验证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseModel<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
//        String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
//        System.out.println(defaultMessage);
        String reduce = e.getBindingResult().getFieldErrors().stream()
            .map(ex -> ex.getField() + ": " + ex.getDefaultMessage())
            .reduce("", (s1, s2) -> s1 + "\n" + s2);
        return ResponseHelper.businessError(reduce);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public ResponseModel<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error(e.getMessage(), e);
        return ResponseHelper.businessError("请求参数不匹配");
    }

    /**
     * 处理所有业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseModel<String> handleBusinessException(BusinessException e) {
        logger.error(e.getMessage(), e);
        return ResponseHelper.businessError(e.getMessage());
    }

}

